package com.example.logdemo;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.Configurator;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP;
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
import ch.qos.logback.core.spi.ContextAwareBase;
import ch.qos.logback.core.util.FileSize;

import java.nio.charset.Charset;

import static ch.qos.logback.core.util.FileSize.GB_COEFFICIENT;

/**
 * @author cxx
 * @create 2021-02-25 9:40
 **/
public class TrackLogConfiguration extends ContextAwareBase implements Configurator {

    @Override
    public void configure(LoggerContext loggerContext) {
        RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<> ();

        String logFile = "/trackLog.log";

        appender.setFile (logFile);
        appender.setName ("trackLog");
        appender.setContext (loggerContext);

        PatternLayoutEncoder patternLayoutEncoder = new PatternLayoutEncoder();
        patternLayoutEncoder.setPattern ("%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %X{rid} %msg%n");
        patternLayoutEncoder.setCharset(Charset.forName ("UTF-8"));
        patternLayoutEncoder.setContext (loggerContext);
        appender.setEncoder (patternLayoutEncoder);
        patternLayoutEncoder.start ();

        TimeBasedRollingPolicy rollingPolicy = new TimeBasedRollingPolicy();
        rollingPolicy.setFileNamePattern(logFile + ".%d{yyyy-MM-dd}.%i");
        rollingPolicy.setParent(appender);
        rollingPolicy.setMaxHistory(5);
        rollingPolicy.setCleanHistoryOnStart(true);
        rollingPolicy.setContext (loggerContext);


        SizeAndTimeBasedFNATP<ILoggingEvent> triggeringPolicy = new SizeAndTimeBasedFNATP<>();
        triggeringPolicy.setMaxFileSize(new FileSize (GB_COEFFICIENT));
        triggeringPolicy.setTimeBasedRollingPolicy(rollingPolicy);
        rollingPolicy.setTimeBasedFileNamingAndTriggeringPolicy(triggeringPolicy);
        rollingPolicy.start ();

        appender.setRollingPolicy (rollingPolicy);
        appender.setTriggeringPolicy (triggeringPolicy);
        appender.start ();
        Logger logger = loggerContext.getLogger ("ROOT");
        logger.addAppender (appender);
    }

}
